package com.linln.admin.pcs.controller;


import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.*;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.persistence.criteria.Predicate;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 服务对象管理
 */
@Controller
@RequestMapping("/pcs/patient")
public class PatientController {

    @Autowired
    private AppService appService;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private PorterConHireLogRepository porterConHireLogRepository;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;

    @Autowired
    private PatientRepository patientRepository;
    @Autowired
    private OrderRepository orderRepository;

    /**
     * 基本信息列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:patient:index")
    public ResponseEntity<?> index(Model model, @EntityParam Patient patient) throws Exception{

        return appService.layTable(patientRepository, before -> {

                    // 添加模板变量
                    return model;

                },

                after -> {


                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("name", QuerySpec.LIKE)
                            .withMatcher("phone", QuerySpec.LIKE)
                            .withMatcher("sex", QuerySpec.EQUAL);
                    String cardNo = HttpServletUtil.getParameter("cardNo");
                    if(cardNo!=null&&cardNo.length()>0){
                        try {
                            querySpec.withMatcherValue("cardNo", QuerySpec.EQUAL, IDCardEncryptor.aesDecrypt(cardNo));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }


                    return QuerySpec.of(querySpec);
                },

                "/pcs/patient/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                 //   List<Porter> list = (List<Porter>) pageResult.getContent();
                    pageResult.getContent().forEach(item -> {
                        // 对每一项数据进行处理
                        Patient data = (Patient) item;

                        //data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        try {
                            data.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(data.getCardNo()));
                            data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                        //1991-12-13 00:00:00
                        if(data.getBirthDate()!=null&&data.getBirthDate().length()>0){
                            data.setBirthDate(data.getBirthDate().substring(0,10));
                        }

                        //data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                    });

                }

        );

    }

    //详情页面
    @GetMapping("/detail")
    @RequiresPermissions("pcs:patient:detail")
    public String detail(Model model) throws Exception{
        Integer id = HttpServletUtil.getParameterInt("id");
        Patient patient = patientRepository.getById(Long.valueOf(id));
        patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
        patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
        if(patient.getBirthDate()!=null&&patient.getBirthDate().length()>0){
            patient.setBirthDate(patient.getBirthDate().substring(0,10));
        }
        model.addAttribute("patient",patient);
        return  "/pcs/patient/detail";
    }

    //打印页面
    @RequestMapping("/print")
    @RequiresPermissions("pcs:patient:print")
    public String print(Model model,@EntityParam String ids) {
        //String ids = HttpServletUtil.getParameter("ids");
        List<Patient> patients = new ArrayList<>();
        if(ids!=null&&ids.length()>0){
            List<Object> patientIds = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherIn("id", patientIds);
            patients = patientRepository.findAll(QuerySpec.of(querySpec));
            patients.forEach(item -> {
                if(item.getBirthDate()!=null&&item.getBirthDate().length()>0){
                    item.setBirthDate(item.getBirthDate().substring(0,10));
                }
            });

        }
        model.addAttribute("patients",patients);
        return  "/pcs/patient/print";
    }

    /**
     * 陪护信息登记
     */
    @GetMapping("/patientOrder")
    @RequiresPermissions("pcs:patient:patientOrder")
    public ResponseEntity<?> patientOrder(Model model) {

        return appService.layTable(orderRepository, before -> {

                    // 添加模板变量
                    return model;

                },

                after -> {


                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("name", QuerySpec.LIKE)
                            .withMatcherValue("type", QuerySpec.EQUAL, "1")
                            .withMatcherValue("orderStatus", QuerySpec.NOT_EQUAL, "-1");
                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/patient/order",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    //   List<Porter> list = (List<Porter>) pageResult.getContent();
                    pageResult.getContent().forEach(item -> {
                        // 对每一项数据进行处理
                        Order data = (Order) item;
                        Patient patient = patientRepository.getById(data.getPatientId());
                        if(patient!=null){
                            data.setSex(patient.getSex());

                            try {
                                data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
                                data.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                             if(patient.getBirthDate()!=null&&patient.getBirthDate().length()>0){
                                data.setBirthDate(patient.getBirthDate().substring(0,10));
                            }
                           // data.setBirthDate(patient.getBirthDate());

                            data.setEthnicity(patient.getEthnicity());
                        }
                    });
                }

        );

    }


    //陪护信息详情页面
    @GetMapping("/orderDetail")
    @RequiresPermissions("pcs:patient:orderDetail")
    public String orderDetail(Model model) throws Exception{
        Integer id = HttpServletUtil.getParameterInt("id");
        Order order = orderRepository.getById(Long.valueOf(id));
        Patient patient = patientRepository.getById(order.getPatientId());
        if(patient.getBirthDate()!=null&&patient.getBirthDate().length()>0){
            patient.setBirthDate(patient.getBirthDate().substring(0,10));
            patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
            patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
        }
        order.setPatient(patient);
        model.addAttribute("order",order);
        return  "/pcs/patient/order_detail";
    }
    //打印页面
    @RequestMapping("/orderPrint")
    @RequiresPermissions("pcs:patient:orderPrint")
    public String orderPrint(Model model,@EntityParam String ids) {
        //String ids = HttpServletUtil.getParameter("ids");
        List<Order> orders = new ArrayList<>();
        if(ids!=null&&ids.length()>0){
            List<Object> patientIds = Arrays.stream(ids.split(","))
                    .map(String::trim)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherIn("id", patientIds);
            orders = orderRepository.findAll(QuerySpec.of(querySpec));
            for (Order order : orders) {
                Patient patient = patientRepository.getById(order.getPatientId());
                if(patient.getBirthDate()!=null&&patient.getBirthDate().length()>0){
                    patient.setBirthDate(patient.getBirthDate().substring(0,10));
                    patient.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(patient.getPhone()));
                    patient.setCardNo(IDCardEncryptor.aesTuoMinDecrypt(patient.getCardNo()));
                }
                order.setPatient(patient);
            }

        }
        model.addAttribute("orders",orders);
        return  "/pcs/patient/order_print";
    }
}
